import { useEffect, useState } from "react"
import { useParams, useHistory } from "react-router-dom"
import {
  queryProcessDetail,
  queryProcessTasks,
  queryProcessComments,
  createProcessComments,
  queryStartForm,
  deleteOne
} from "../../apis/processInstances"
import { Button, Spin, Card, Timeline, Space, message, Modal } from 'antd'
import CommentList from "../../components/CommentList"
import { formatTime } from "../../utils/time"
import CommonModalForm from "../../components/common/CommonModalForm"
import useCURD from "../../hooks/useCURD"
import DetailHeader from "../../components/DetailHeader"
import { formatFormItems } from "../../utils/formItems"
import { queryTaskForm } from "../../apis/task"
import ProcessPreviewModal from "../../components/ProcessDesigner/preview/ProcessPreviewModal"


const ProcessCommentList = ({
  processInstanceId
}) => {
  const {
    listData,
    handleCreate,
    handleCancelForm,
    handleSubmit,
    formVisible,
    formTitle,
  } = useCURD({
    apis: {
      queryList: queryProcessComments,
      createOne: createProcessComments
    },
    moduleName: '评论',
    defaultQuery: {
      pid: processInstanceId,
      latestFirst: true
    },
    defaultSubmitValues: {
      pid: processInstanceId,
    }
  })

  const formItems = [
    {
      label: '评论内容',
      name: 'message',
      required: true
    }
  ]

  return <Card
    title="评论"
    extra={
      <a type="link" onClick={handleCreate}>添加评论</a>
    }
    size="small"
  >
    <CommonModalForm
      title={formTitle}
      visible={formVisible}
      onCancel={handleCancelForm}
      onSubmit={handleSubmit}
      formItems={formItems}
    ></CommonModalForm>
    <CommentList
      listData={listData}
    ></CommentList>
  </Card>
}

const WorkflowProcessDetail = ({ }) => {
  const { id } = useParams()
  const history = useHistory()
  const [loading, setLoading] = useState(false)

  const [detail, setDetail] = useState({})
  const [currentTask, setCurrentTask] = useState(null)
  const [completeTasks, setCompleteTasks] = useState([])

  const doQueryDetail = async () => {
    if (id) {
      if (!loading) {
        setLoading(true)
        try {
          // 流程实例详情
          const detail = await queryProcessDetail(id)
          setDetail(detail)

          // 当前任务
          const {
            data: currentTask
          } = await queryProcessTasks({
            processInstanceId: id
          })
          if (currentTask && currentTask.length > 0) {
            setCurrentTask(currentTask[0])
          }

          // 完成的任务
          const {
            data: completeTasks
          } = await queryProcessTasks({
            processInstanceId: id,
            state: 'completed'
          })
          completeTasks.reverse()
          setCompleteTasks(completeTasks)

          // 评论
          // const {
          //   data
          // } = await queryProcessComments(id)
          // setComments(data)

          setLoading(false)
        } catch (error) {
          setLoading(false)
        }
      }
    }
  }

  useEffect(() => {
    doQueryDetail()
  }, [])


  const [formProps, setFormProps] = useState({
    visible: false,
    formItems: [],
    initValues: {}
  })

  const handleShowTaskForm = async (task) => {
    try {
      const res = await queryTaskForm(task.id)
      const formItems = formatFormItems(res.fields)
      const initValues = {}
      res.fields.forEach(el => {
        if (el.type === 'date' && el.value && el.value.split('-')[0].length !== 4) {
          initValues[el.id] = el.value.split('-').reverse().join('-')
        } else {
          initValues[el.id] = el.value
        }
      })
      setFormProps({
        title: task.name,
        disabled: true,
        visible: true,
        formItems: formItems,
        initValues: initValues
      })
    } catch (error) {
      message.error('查询失败')
    }
  }

  const handleShowForm = async () => {
    try {
      const res = await queryStartForm(id)
      const formItems = formatFormItems(res.fields)
      const initValues = {}
      res.fields.forEach(el => {
        if (el.type === 'date' && el.value && el.value.split('-')[0].length !== 4) {
          initValues[el.id] = el.value.split('-').reverse().join('-')
        } else {
          initValues[el.id] = el.value
        }
      })
      setFormProps({
        title: '流程提交表单',
        disabled: true,
        visible: true,
        formItems: formItems,
        initValues: initValues
      })
    } catch (error) {
      message.error('查询失败')
    }
  }

  const handleDelete = () => {
    Modal.confirm({
      title: '确定要取消流程?',
      onOk: async () => {
        try {
          await deleteOne(id)
          message.success('取消成功')
          history.goBack()
        } catch (error) {
          message.error('取消失败')
        }
      }
    })
  }

  return <Spin spinning={loading} wrapperClassName="page-wrap">
    <CommonModalForm
      {...formProps}
      onCancel={() => {
        setFormProps({
          title: '',
          visible: false,
          formItems: [],
          initValues: {}
        })
      }}
    ></CommonModalForm>
    <DetailHeader
      title={<b style={{ fontSize: 16 }}>{detail.name}</b>}
      extra={
        <Space>
          <ProcessPreviewModal
            processDefinitionId={id}
            isFinish={!!detail.ended}
          ></ProcessPreviewModal>
          <Button type="primary" danger onClick={handleDelete}>取消流程</Button>
        </Space>
      }
    ></DetailHeader>
    <div className="page-body" style={{ display: "flex" }}>
      <div style={{ height: '100%', flex: 1, marginRight: 20, overflow: 'auto' }}>
        <Card title="任务" size="small">
          <div style={{ height: 30 }}></div>
          <Timeline mode="left">
            {
              currentTask && <Timeline.Item
                color="red"
                label={formatTime(currentTask?.created)}
              >
                <div>
                  <div>{currentTask?.name}</div>
                  {
                    currentTask?.assignee ?
                      <div>
                        <span style={{ color: '#999' }}>待执行人：</span>
                        {currentTask.assignee.fullName}
                      </div> :
                      <div><span style={{ color: '#ccc' }}>任务未被认领</span></div>
                  }
                </div>
              </Timeline.Item>
            }
            {
              completeTasks.map(el => {
                return <Timeline.Item
                  color="green"
                  key={el.id}
                  label={formatTime(el.endDate)}
                ><div>
                    <div>{el.name}

                      {
                        el.formKey && <Button
                          style={{ marginLeft: 20 }}
                          size="small"
                          onClick={() => {
                            handleShowTaskForm(el)
                          }}
                        >查看表单</Button>
                      }
                    </div>
                    <div>
                      <span style={{ color: '#999' }}>执行人：</span>
                      {el.assignee.fullName}
                    </div>
                  </div></Timeline.Item>
              })
            }
            <Timeline.Item
              label={formatTime(detail.started)}
            >
              <div>
                <div>流程提交
                  {
                    detail.startFormDefined && <Button
                      style={{ marginLeft: 20 }}
                      size="small"
                      onClick={handleShowForm}
                    >查看表单</Button>
                  }
                </div>
                <div>
                  <span style={{ color: '#999' }}>提交人：</span>
                  {detail.startedBy?.fullName}
                </div>
              </div>
            </Timeline.Item>
          </Timeline>
        </Card>
      </div>
      <div style={{ height: '100%', width: 300, overflow: 'auto' }}>
        <ProcessCommentList
          processInstanceId={id}
        ></ProcessCommentList>
      </div>
    </div>
  </Spin>
}

export default WorkflowProcessDetail